package com.yang.strategy;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Component
public class StrategyFactory implements ApplicationContextAware {

    private static Map<String, TestStrategy> testServiceMap;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        testServiceMap = new HashMap<>(16);
        // 通过applicationContext.getBeansOfType 动态获取接口的所有实现类
        Map<String, TestStrategy> map = applicationContext.getBeansOfType(TestStrategy.class);
        map.forEach((key, value) -> {
            testServiceMap.put(value.getCode(), value);
        });

    }

    public static TestStrategy getStrategy(String code){
        TestStrategy testStrategy = testServiceMap.get(code);
        if (Objects.isNull(testStrategy)) {
            // 如果通过自定义编码没能找到具体实现类， 去执行默认的实现类代码
            return testServiceMap.get("default");
        } else
            return testStrategy;
    }
}
